package com.weige.conver.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weige.conver.entity.*;
import com.weige.conver.handler.ConverContext;
import com.weige.conver.handler.ConverHandler;
import com.weige.conver.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;

@Service
@Slf4j
public class ConverService {
    private int errorFlag = 0;
    @Autowired
    private SwitchCabinetService switchCabinetService;
    private ConfigService configService = new ConfigService();

    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.username}")
    private String userName;
    @Value("${spring.rabbitmq.password}")
    private String passWord;
    @Value("${spring.rabbitmq.port}")
    private Integer port;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;
    @Value("${CoverQueue}")
    private String CoverQueue;
    @Value("${RoutingKey}")
    private String RoutingKey;
    @Value("${Exchange}")
    private String Exchange;

    /**
     * 存储上传的动环设备信息
     */
    public static Map<String,ReceiveMessage> envDataMap = new HashMap();

    /**
     * 存储上传的开关柜设备信息
     */
    public static Map<String,ReceiveMessage> switchCabinetDataMap = new HashMap();

//    /**
//     * rabbitMQ监测动环数据
//     *
//     * @param message
//     * @throws IOException
//     * @throws TimeoutException
//     */
//    @RabbitListener(queues = "${spring.rabbitmq.envqueue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByEnv(String message){
//        HashMap envData = mqDataTOMQTT(message);
//        if (envData == null) {
//            return;
//        } else {
//            try {
//                //广州局站临时增加
//                String devId = (String) envData.get("devId");
//                String devName = InitController.deviceMap.get(devId);
//                if (WindID.equals(devId)){
//                    envData.put("type","8");
//                }else {
//                    envData.put("type","0");
//                }
//                envData.put("devName",devName);
//                //-------------
//                getReceiveMessage(envData);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * rabbitMQ监测特变数据
     *
     * @param message
     * @throws IOException
     * @throws TimeoutException
     */
    @RabbitListener(queues = "${spring.rabbitmq.envqueue}")
    @RabbitHandler
    public void mqSendMessageToMqttByEnv(String message){
        execute(message);
    }

    /**
     * rabbitMQ监测动环数据
     *
     * @param message
     * @throws IOException
     * @throws TimeoutException
     */
    @RabbitListener(queues = "${spring.rabbitmq.wgqueue}")
    @RabbitHandler
    public void mqSendMessageToMqttByWgEnv(String message){
        execute(message);
    }

//
//    @RabbitListener(queues = "${spring.rabbitmq.firequeue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByFireAlarm(String message){
//        execute(message);
//    }
//
//    @RabbitListener(queues = "${spring.rabbitmq.groundqueue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByGround(String message){
//        execute(message);
//    }


//    /**
//     * rabbitMQ监测GIS_IED数据
//     *
//     * @param message
//     * @throws IOException
//     * @throws TimeoutException
//     */
//    @RabbitListener(queues = "${spring.rabbitmq.gisiedqueue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByGisIed(String message) throws IOException {
//        HashMap envData = mqDataTOMQTT(message);
//        if (envData == null) {
//            return;
//        } else {
//            getReceiveMessage(envData);
//        }
//    }
//
//    /**
//     * rabbitMQ监测主变数据
//     *
//     * @param message
//     * @throws IOException
//     * @throws TimeoutException
//     */
//    @RabbitListener(queues = "${spring.rabbitmq.zhubianiedqueue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByMainTransformer(String message) throws IOException {
//        HashMap envData = mqDataTOMQTT(message);
//        if (envData == null) {
//            return;
//        } else {
//            getReceiveMessage(envData);
//        }
//    }
//
//    /**
//     * rabbitMQ监测消防安全告警数据
//     *
//     * @param message
//     * @throws IOException
//     * @throws TimeoutException
//     */
//    @RabbitListener(queues = "${spring.rabbitmq.firequeue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttByFire(String message) throws IOException {
//        JSONObject messageToJSON = JSONObject.parseObject(message);
//        JSONObject param = messageToJSON.getJSONObject("param");
//        if (param == null) {
//            return;
//        } else {
//            String devId = param.getString("devId");
//            String devName = param.getString("devName");
//            String data = param.getString("points");
//            ReceiveMessage receiveMessage = new ReceiveMessage(devId,21,devName,data);
//            ConverHandler converHandler = ConverContext.getInstance("21");
//            converHandler.handler(receiveMessage);
//        }
//    }
//
    /**
     * rabbitMQ监测开关柜数据
     *
     * @param
     * @throws IOException
     * @throws TimeoutException
     */
    @RabbitListener(queues = "${spring.rabbitmq.switchcabinetqueue}")
    @RabbitHandler
    public void mqSendMessageToMqttBySwitchCabinet(String message) throws IOException, InterruptedException {
        switchCabinetService.sendSwitchCabinetDataToMQTT(message);
    }
//
//    @RabbitListener(queues = "${spring.rabbitmq.sczdjgqueue}")
//    @RabbitHandler
//    public void mqSendMessageToMqttBySwitchCabinetDiagnoseResult(String message){
//        try {
//            switchCabinetService.sendSwitchCabinetDiagnoseResultDataToMQTT(message);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public void execute(String message){
        HashMap envData = mqDataTOMQTT(message);
        if (envData == null) {
            return;
        } else {
            try {
                getReceiveMessage(envData);
            }catch (Exception e){
                errorFlag ++;
                if (errorFlag >= 0 && errorFlag <= 20){
                    log.error("*****ConverService类receiveData方法报错第"+errorFlag+"次，报错日志：**********" );
                    log.error(ExceptionUtils.getStackTraceInfo(e));
                }
            }
        }
    }

    private void getReceiveMessage(HashMap data) throws IOException {
        String devId = (String) data.get("devId");
        String type = (String) data.get("type");
        String devName = (String) data.get("devName");
        String value = (String) data.get("sigValue");
        String desc = (String) data.get("sigDescription");
        ReceiveMessage receiveMessage = new ReceiveMessage(devId,Integer.valueOf(type),devName,value,desc);
        envDataMap.put(devId,receiveMessage);
        ConverHandler converHandler = ConverContext.getInstance(String.valueOf(receiveMessage.getType()));
        converHandler.handler(receiveMessage);
    }

    public HashMap mqDataTOMQTT(String data) {
        HashMap<String, Object> map = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(data);
        Iterator iterator = jsonObject.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            String val = jsonObject.getString(key);
            boolean flag = val.startsWith("{");
            boolean flag2 = val.startsWith("[{");
            if (flag) {
                JSONObject jsonVal = JSON.parseObject(val);
                Iterator iteratorVal = jsonVal.keySet().iterator();
                while (iteratorVal.hasNext()) {
                    String keyVal = (String) iteratorVal.next();
                    map.put(keyVal, jsonVal.getString(keyVal));
                }
            } else if (flag2) {
                JSONArray jsonArray = JSON.parseArray(val);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    Iterator iteratorVal = object.keySet().iterator();
                    while (iteratorVal.hasNext()) {
                        String keyVal = (String) iteratorVal.next();
                        String keyData = object.getString(keyVal);
                        boolean flag3 = keyData.startsWith("{");
                        if (flag3) {
                            JSONObject jsonVal2 = JSON.parseObject(keyData);
                            Iterator iteratorVal2 = jsonVal2.keySet().iterator();
                            while (iteratorVal2.hasNext()) {
                                String keyVal2 = (String) iteratorVal2.next();
                                map.put(keyVal2, jsonVal2.getString(keyVal2));
                            }
                        } else {
                            map.put(keyVal, keyData);
                        }
                    }
                }
            } else {
                map.put(key, jsonObject.getString(key));
            }
        }
        Map conver = configService.getConfigData();
        if (conver.isEmpty()){
            conver = JsonUtils.GetAreaCode("data.json");
        }
        HashMap<Object, Object> object = new HashMap();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String s = (String) it.next();
            for (Object d : conver.keySet()) {
                if (s.equals(d)) {
                    object.put(conver.get(d), map.get(s));
                }
            }
        }
        return object;
    }
}
